<template>
  <div class="base-leaflet-map">
    <div id="leaflet-map"></div>
    <template v-if="isBaseMapDone">
      <slot />
    </template>
  </div>
</template>

<script setup lang="ts">
import 'leaflet/dist/leaflet.css'
import * as L from 'leaflet'
import { LMap } from '@quickearth/leaflet'
import { useBaseLeafletMapStore } from '@/store/modules/baseLeafletMap'
import yulinGeojson from '@/assets/data/yulin1.json'
import taiyuanQxjson from '@/assets/data/taiyuan-qx.json'
import '@geoman-io/leaflet-geoman-free'
import '@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css'
import 'leaflet-polylinedecorator'
import 'leaflet-ant-path'
const props = defineProps({
  options: {
    default: () => ({
      attributionControl: false,
      zoomControl: false,
      minZoom: 3,
      maxZoom: 15,
      zoomSnap: 0.1,
      preferCanvas: true,
      renderer: L.canvas()
    })
  }
})

const baseLeafletMapStore = useBaseLeafletMapStore()

// const tdtToken = 'cc94e978d9bdc0e6655fa2cdb83fe210'

const baseMap = ref('')
provide('baseMap', baseMap)

const isBaseMapDone = ref(false)

const handleInitMap = () => {
  baseMap.value = new LMap('leaflet-map', {
    crs: L.CRS.EPSG3857,
    ...props.options,
    minZoom: 7,
    maxZoom: 11
  }).setView([37.36, 112.14], 7.2)

  // 实时经纬度事件
  baseMap.value.on('mousemove', e => {
    useEventBus('currentMapPositionLatLng').emit(
      e.latlng.lng.toFixed(4),
      e.latlng.lat.toFixed(4)
    )
  })

  baseMap.value.pm.setLang('zh')

  baseLeafletMapStore.baseMap = baseMap.value

  L.Popup.prototype._animateZoom = function (e) {
    if (!this._map) {
      return
    }
    const pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center)
    const anchor = this._getAnchor()
    L.DomUtil.setPosition(this._container, pos.add(anchor))
  }
  // 监听地图缩放事件
  baseMap.value.on('zoomend', function (et) {
    getMapScale()
  })
  // 监听地图mousemove事件
  baseMap.value.on('mousemove', function (et) {
    baseLeafletMapStore.cameraPos = {
      lat: et.latlng.lat,
      lng: et.latlng.lng
    }
  })
  // 关闭双击缩放
  baseMap.value.doubleClickZoom.disable()

  isBaseMapDone.value = true

  // 地图加载完毕事件
  useEventBus('baseLeafletMapInitDone').emit('')
}

const layerList = reactive({})

// 添加图层
const handleAddLayer = (layer, layerName) => {
  layerList[layerName] = layer.addTo(baseMap.value)
}
useEventBus('handleAddLayer').on(handleAddLayer)

// 移除图层
const handleRemoveLayer = layerName => {
  if (layerList[layerName]) {
    baseMap.value.removeLayer(layerList[layerName])
    delete layerList[layerName]
  }
}
useEventBus('handleRemoveLayer').on(handleRemoveLayer)

// 移除全部图层
const handleRemoveAllLayer = () => {
  Object.keys(layerList).forEach(item => {
    baseMap.value.removeLayer(layerList[item])
  })
}
useEventBus('handleRemoveAllLayer').on(handleRemoveAllLayer)

// 跳转视野
const flyTo = options => {
  baseMap.value.flyTo([options.lat, options.lon], options.zoom)
}
useEventBus('handleFlyTo').on(flyTo)
// 放大视野
const enlarge = () => {
  baseMap.value.zoomIn()
  getMapScale()
}
useEventBus('handleEnlarge').on(enlarge)
// 缩小视野
const narrow = () => {
  baseMap.value.zoomOut()
  getMapScale()
}
useEventBus('handleNarrow').on(narrow)

// 初始化摄像机位置
const initCameraPosition = () => {
  console.log(111)

  // 设置相机位置
  baseMap.value.setView([37.36, 112.14], 7.2)
}
useEventBus('handleInitCameraPosition').on(initCameraPosition)

//绘制地图
const initLayer = (json, { name, select }) => {
  handleAddLayer(
    L.geoJSON(json, {
      style: {
        fillColor: 'transparent',
        weight: 1,
        opacity: 0.3,
        color: '#333',
        fillOpacity: 0
      }
    }),
    name
  )
}
// const layer = L.layerGroup().addTo(toRaw(baseMap.value))
useEventBus('handleInitLayer').on(initLayer)
let isQXLayer = ref(false)
// 获取当前地图的缩放级别
const getMapScale = () => {
  const zoomLevel = baseMap.value.getZoom()
  // 根据缩放级别估算地图视图下的实际距离（示例计算）
  const earthRadius = 6371 // 地球半径（单位：公里）
  const mapWidth = 256 * Math.pow(2, zoomLevel) // 地图宽度（单位：像素）
  const pixelWidth = baseMap.value._container.clientWidth // 地图容器宽度（单位：像素）
  const kmPerPixel = (2 * Math.PI * earthRadius) / mapWidth // 每个像素代表的公里数
  const mapScale = (pixelWidth * kmPerPixel).toFixed(0) // 当前地图视图下的实际距离（单位：公里）

  // 在页面上显示地图尺寸信息
  baseLeafletMapStore.kilometre = `${mapScale}公里`
  if (baseLeafletMapStore.cameraPos) {
    const el = isCounty(baseLeafletMapStore.cameraPos)
    if (zoomLevel < 9) {
      useEventBus('handleRemoveLayer').emit('shanxiQuXian')
      baseLeafletMapStore.selectCity = null
      baseLeafletMapStore.cameraPos = null
      isQXLayer.value = false
      return
    } else {
      if (isQXLayer.value) return
      useEventBus('handleInitLayer').emit(el, {
        name: 'shanxiQuXian',
        select: 'none'
      })
      baseLeafletMapStore.selectCity = el.features
      isQXLayer.value = true
    }
  } else {
    useEventBus('handleRemoveLayer').emit('shanxiQuXian')
  }
}
const isCounty = pos => {
  let obj = {}
  yulinGeojson.features.forEach(feature => {
    if (feature.geometry.type == 'MultiPolygon') {
      feature.geometry.coordinates.forEach(element => {
        element.forEach(polygon => {
          if (isPointInPolygon(pos.lng, pos.lat, polygon)) {
            let countyName = feature.properties.name // 假设区县名称存储在属性中的'name'字段中
            taiyuanQxjson.features.forEach(el => {
              if (countyName == el.parent) {
                obj = el
              }
            })
          }
        })
      })
    }
  })
  return obj
}
//查找当前点击区县名称
const isPointInPolygon = (lng, lat, polygon) => {
  let inside = false
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    let xi = polygon[i][0],
      yi = polygon[i][1]
    let xj = polygon[j][0],
      yj = polygon[j][1]

    let intersect =
      yi > lat !== yj > lat && lng < ((xj - xi) * (lat - yi)) / (yj - yi) + xi
    if (intersect) inside = !inside
  }
  return inside
}
onMounted(() => {
  handleInitMap()
  initCameraPosition()
  getMapScale()
})

onUnmounted(() => {
  handleRemoveAllLayer()
  baseMap.value.remove()
})
</script>

<style scoped lang="scss">
.base-leaflet-map {
  width: 100%;
  height: 100%;

  #leaflet-map {
    width: 100%;
    height: 100%;
    position: relative;
  }
}
</style>

<style lang="scss">
.leaflet-div-icon {
  background-color: unset;
  border: none;
}
.leaflet-popup-content {
  p {
    margin: 0;
  }
}

.leaflet-popup {
  .leaflet-popup-content-wrapper {
    box-shadow: none;
    .leaflet-popup-content {
      margin: 0;
      width: 0 !important;
      height: 0;
    }
  }
  .leaflet-popup-tip-container,
  .leaflet-popup-close-button {
    display: none;
  }
}
// 强行提高filled-pane层级
// .leaflet-filled-pane{
//   z-index: 500 !important;
// }
</style>
